/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.daydream.wrapper.commons.jackson;

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ValueInstantiator;
import com.fasterxml.jackson.databind.deser.std.ReferenceTypeDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;

import org.pajamas.daydream.wrapper.commons.ImmutableWrapper;
import org.pajamas.protocol.Wrapper;

/**
 * @author william
 * @since 2023/12/31
 */

final class ImmutableWrapperDeserializer
        extends ReferenceTypeDeserializer<Wrapper<?>> {
    private static final long serialVersionUID = 3910354418844977809L;

    public ImmutableWrapperDeserializer(JavaType fullType, ValueInstantiator inst,
                                        TypeDeserializer typeDeser, JsonDeserializer<?> deser) {
        super(fullType, inst, typeDeser, deser);
    }

    @Override
    public ImmutableWrapperDeserializer withResolved(TypeDeserializer typeDeser, JsonDeserializer<?> valueDeser) {
        return new ImmutableWrapperDeserializer(_fullType, _valueInstantiator,
                typeDeser, valueDeser);
    }

    @Override
    public Wrapper<?> getNullValue(DeserializationContext ctxt) throws JsonMappingException {
        return ImmutableWrapper.of(_valueDeserializer.getNullValue(ctxt));
    }

    @Override
    public Object getEmptyValue(DeserializationContext ctxt) throws JsonMappingException {
        return getNullValue(ctxt);
    }

    @Override
    public Wrapper<?> referenceValue(Object contents) {
        return ImmutableWrapper.of(contents);
    }

    @Override
    public Object getReferenced(Wrapper<?> reference) {
        return reference.unwrap();
    }

    @Override
    public Wrapper<?> updateReference(Wrapper<?> reference, Object contents) {
        return ImmutableWrapper.of(contents);
    }
}
